package com.jt.sys.service.impl;

import java.util.List;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.jt.common.annotation.RequestLog;
import com.jt.common.exception.ServiceException;
import com.jt.common.vo.CheckBox;
import com.jt.common.vo.PageObject;
import com.jt.common.vo.SysUserDeptResult;
import com.jt.sys.dao.SysMenuDao;
import com.jt.sys.dao.SysRoleDao;
import com.jt.sys.dao.SysRoleMenuDao;
import com.jt.sys.dao.SysUserDao;
import com.jt.sys.dao.SysUserRoleDao;
import com.jt.sys.entity.SysUser;
import com.jt.sys.service.SysUserService;
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;
	@Autowired
	private SysMenuDao sysMenuDao;
	@Override
	@RequestLog("查看用户信息")
	public PageObject<SysUserDeptResult> findPageObjects(String username, Integer pageCurrent) {
		System.out.println(username);
		if(pageCurrent==null||pageCurrent<1)
			throw new IllegalArgumentException("输入的页码不合法");
		Integer pageSize=6;
		Integer startIndex=(pageCurrent-1)*pageSize;
		int rowCount = sysUserDao.getRowCount(username);
		if(rowCount==0)
			throw new ServiceException("当前页没有记录");
		List<SysUserDeptResult> records = sysUserDao.findPageObjects(username, startIndex, pageSize);
		PageObject<SysUserDeptResult> pObject = new PageObject<SysUserDeptResult>();
		pObject.setPageCurrent(pageCurrent);
		pObject.setPageSize(pageSize);
		pObject.setRecords(records);
		pObject.setRowCount(rowCount);
		return pObject;
	}
	
	//@RequiresPermissions("sys:user:valid")
	@Override
	@RequestLog("禁用启用用户登陆")
	public int validById(Integer id, Byte valid) {
		if(id==null||id<1)
			throw new IllegalArgumentException("id值无效");
		if(valid==null||valid!=1&&valid!=0)
			throw new IllegalArgumentException("valid值无效");
		int rows = sysUserDao.validById(id, valid);
		if(rows==0)
			throw new ServiceException("记录可能已经不存在了");
		return rows;
	}
	@Override
	@RequestLog("添加用户信息")
	public int saveObject(SysUser entity, Integer[] roleIds) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getUsername()))
			throw new ServiceException("用户名不能为空");
		if(StringUtils.isEmpty(entity.getPassword()))
			throw new ServiceException("用户密码不能为空");
		if(StringUtils.isEmpty(roleIds))
			throw new ServiceException("必须要选择一个角色");
		String salt=UUID.randomUUID().toString();
		String pwd=entity.getPassword();
		SimpleHash simpleHash = new SimpleHash(
				"MD5", //加密算法
				pwd, //要加密的资源
				salt);//
		String newPwd=simpleHash.toString();
		entity.setSalt(salt);
		entity.setPassword(newPwd);
		entity.setCreatedUser("admin");
		entity.setModifiedUser("admin");
		int rows;
		try {
			rows = sysUserDao.insertObject(entity);
		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof DuplicateKeyException){
				throw new ServiceException("此用户已存在");
			}
			throw new ServiceException("系统维护");
		}
		try {
			sysUserRoleDao.insetObject(entity.getId(), roleIds);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统维护中");
		}
		return rows;
	}
	@Override
	public List<CheckBox> findRoles() {
		return sysRoleDao.findObjects();
	}
	@Override
	@RequestLog("修改用户信息")
	public int updateObject(SysUser entity, Integer[] roleIds) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getUsername()))
			throw new ServiceException("用户名不能为空");
		if(StringUtils.isEmpty(entity.getPassword()))
			throw new ServiceException("用户密码不能为空");
		if(StringUtils.isEmpty(roleIds))
			throw new ServiceException("必须要选择一个角色");
		String salt=UUID.randomUUID().toString();
		String pwd = entity.getPassword();
		SimpleHash simpleHash = new SimpleHash("MD5", pwd, salt);
		String newPwd = simpleHash.toString();
		entity.setSalt(salt);
		entity.setPassword(newPwd);
		entity.setCreatedUser("admin");
		entity.setModifiedUser("admin");
		int rows;
		try {
			rows = sysUserDao.updateObject(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统维护");
		}
		try {
			sysUserRoleDao.deleteObjectByUserId(entity.getId());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("该信息不存在");
		}
		try {
			sysUserRoleDao.insetObject(entity.getId(), roleIds);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统维护中");
		}
		return rows;
	}

	@Override
	public List<String> findPermissionsByUsername(String username) {
		int userId = sysUserDao.findIdByUsername(username);
		List<Integer> list = sysUserRoleDao.findRoleIdsByUserId(userId);
		Integer[] array = list.toArray(new Integer[]{});
		//3.基于用户角色Id查找菜单id
		List<Integer> list2 = sysRoleMenuDao.findMenuIdsByRoleId(array);
		Integer[] array2=list2.toArray(new Integer[]{});
		//4.基于菜单Id查找权限标识
//		Set<String> pSet=new HashSet<>();
		List<String> permissions = sysMenuDao.findPermissions(array2);
		return permissions;
	}
	
	@Override
	public void login(String username, String password){
		//0.参数合法性验证
		if(StringUtils.isEmpty(username))
		throw new ServiceException("用户名不能为空");
		if(StringUtils.isEmpty(password))
		throw new ServiceException("密码不能为空");
		//获取Subject主体对象
		Subject subject = SecurityUtils.getSubject();
		//封装用户及密码
		UsernamePasswordToken token=new UsernamePasswordToken(username,password);
		//执行身份认证
		try {
			subject.login(token);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("用户名或密码不正确");
		}
		//记录用户信息
		Session session=SecurityUtils.getSubject().getSession();
		session.setAttribute("username", username);
	}
	
}
